<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card" v-for="item in statCards" :key="item.label">
        <div class="stat-icon" :class="item.iconClass">
          <el-icon><component :is="item.icon" /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ item.value }}</div>
          <div class="stat-label">{{ item.label }}</div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-grid">
      <div class="chart-card">
        <div class="chart-header">
          <h3>文章发布趋势</h3>
        </div>
        <div class="chart-content">
          <div ref="articleChart" class="chart"></div>
        </div>
      </div>
      <div class="chart-card">
        <div class="chart-header">
          <h3>分类文章分布</h3>
        </div>
        <div class="chart-content">
          <div ref="categoryChart" class="chart"></div>
        </div>
      </div>
    </div>

    <!-- 最新动态 -->
    <div class="recent-section">
      <div class="recent-articles">
        <div class="section-header">
          <h3>最新文章</h3>
        </div>
        <div class="article-list">
          <div v-for="article in recentArticles" :key="article.id" class="article-item">
            <div class="article-info">
              <h4>{{ article.title }}</h4>
              <div class="article-meta">
                <span>{{ formatDate(article.created_at) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="recent-messages">
        <div class="section-header">
          <h3>最新留言</h3>
        </div>
        <div class="message-list">
          <div v-for="message in recentMessages" :key="message.id" class="message-item">
            <div class="message-info">
              <h4>{{ message.guest_name }}</h4>
              <p>{{ message.content }}</p>
              <div class="message-meta">
                <span>{{ formatDate(message.created_at) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="recent-photos">
        <div class="section-header">
          <h3>最新图片</h3>
        </div>
        <div class="photo-list">
          <div v-for="photo in recentPhotos" :key="photo.id" class="photo-item">
            <img :src="photo.url" :alt="photo.title" class="photo-thumb" />
            <div class="photo-info">
              <span>{{ photo.title }}</span>
              <span>{{ formatDate(photo.created_at) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { statsApi } from '@/api/admin'
import {
  Document,
  Folder,
  ChatDotRound,
  Picture,
  CollectionTag,
  User,
  ChatLineRound,
  ChatSquare,
} from '@element-plus/icons-vue'

// 统计数据
const stats = ref({
  total_articles: 0,
  published_articles: 0,
  total_categories: 0,
  total_tags: 0,
  total_users: 0,
  total_messages: 0,
  total_photos: 0,
  total_comments: 0
})
const recentArticles = ref([])
const recentMessages = ref([])
const recentPhotos = ref([])

// 卡片配置
const statCards = computed(() => [
  { label: '文章总数', value: stats.value.total_articles, icon: Document, iconClass: 'articles' },
  { label: '已发布', value: stats.value.published_articles, icon: ChatLineRound, iconClass: 'published' },
  { label: '分类总数', value: stats.value.total_categories, icon: Folder, iconClass: 'categories' },
  { label: '标签总数', value: stats.value.total_tags, icon: CollectionTag, iconClass: 'tags' },
  { label: '用户总数', value: stats.value.total_users, icon: User, iconClass: 'users' },
  { label: '留言总数', value: stats.value.total_messages, icon: ChatDotRound, iconClass: 'messages' },
  { label: '图片总数', value: stats.value.total_photos, icon: Picture, iconClass: 'photos' },
  { label: '评论总数', value: stats.value.total_comments, icon: ChatSquare, iconClass: 'comments' },
])

// 图表实例
let articleChart = null
let categoryChart = null

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const res = await statsApi.getDashboardStats()
    const data = res.data
    stats.value = data
    recentArticles.value = data.recent_articles || []
    recentMessages.value = data.recent_messages || []
    recentPhotos.value = data.recent_photos || []
  } catch (error) {
    ElMessage.error('获取统计数据失败')
  }
}

// 获取文章趋势数据
const fetchArticleTrend = async (period = 'month') => {
  try {
    const res = await statsApi.getArticleStats({ period })
    console.log(res)
    return res.data
  } catch (error) {
    return []
  }
}

// 获取分类分布数据
const fetchCategoryDist = async () => {
  try {
    const res = await statsApi.getCategoryStats()
    return res.data
  } catch (error) {
    return []
  }
}

// 初始化文章趋势图表
const initArticleChart = async () => {
  const chartDom = document.querySelector('.chart')
  if (!chartDom) return
  articleChart = echarts.init(chartDom)
  const trend = await fetchArticleTrend('month')
  const xData = trend.map(item => item.date)
  const yData = trend.map(item => item.count)
  const option = {
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: xData },
    yAxis: { type: 'value' },
    series: [{
      data: yData,
      type: 'line',
      smooth: true,
      areaStyle: { opacity: 0.3 }
    }]
  }
  articleChart.setOption(option)
}

// 初始化分类分布图表
const initCategoryChart = async () => {
  const chartDom = document.querySelectorAll('.chart')[1]
  if (!chartDom) return
  categoryChart = echarts.init(chartDom)
  const dist = await fetchCategoryDist()
  const option = {
    tooltip: { trigger: 'item' },
    series: [{
      type: 'pie',
      radius: '50%',
      data: dist.map(item => ({ value: item.articles_count, name: item.name }))
    }]
  }
  categoryChart.setOption(option)
}

onMounted(async () => {
  await fetchStats()
  setTimeout(() => {
    initArticleChart()
    initCategoryChart()
  }, 100)
})
onUnmounted(() => {
  if (articleChart) articleChart.dispose()
  if (categoryChart) categoryChart.dispose()
})
</script>

<style scoped lang="scss">
.dashboard {
  background: #fafbfc;
  min-height: 100vh;
  padding: 32px 0;
}
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}
.stat-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  padding: 24px 18px;
  display: flex;
  align-items: center;
  gap: 14px;
  .stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    color: #fff;
    &.articles { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
    &.published { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
    &.categories { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
    &.tags { background: linear-gradient(135deg, #f7971e 0%, #ffd200 100%); }
    &.users { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
    &.messages { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
    &.photos { background: linear-gradient(135deg, #f7971e 0%, #ffd200 100%); }
    &.comments { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
  }
  .stat-content {
    .stat-number { font-size: 28px; font-weight: 700; color: #222; line-height: 1; }
    .stat-label { font-size: 13px; color: #888; margin-top: 4px; }
  }
}
.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}
.chart-card {
  background: #fff;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  .chart-header { margin-bottom: 16px; h3 { margin: 0; font-size: 18px; color: #222; } }
  .chart-content { .chart { height: 300px; } }
}
.recent-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(340px, 1fr));
  gap: 24px;
}
.recent-articles, .recent-messages, .recent-photos {
  background: #fff;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  .section-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; h3 { margin: 0; font-size: 18px; color: #222; } }
}
.article-item, .message-item, .photo-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  &:last-child { border-bottom: none; }
  .article-info, .message-info, .photo-info {
    flex: 1;
    h4 { margin: 0 0 8px 0; font-size: 16px; color: #222; }
    p { margin: 0 0 8px 0; font-size: 14px; color: #555; line-height: 1.5; }
    span { font-size: 12px; color: #888; margin-right: 8px; }
  }
  .photo-thumb { width: 60px; height: 60px; object-fit: cover; border-radius: 8px; margin-right: 12px; }
}
@media (max-width: 768px) {
  .dashboard {
    .stats-grid { grid-template-columns: 1fr; }
    .charts-grid { grid-template-columns: 1fr; }
    .recent-section { grid-template-columns: 1fr; }
  }
}
</style> 